﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using System.Security;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using EarringsBackEnd.Properties;

namespace EarringsBackEnd
{
    public partial class frmEarringMaster : Form
    {
        private Bitmap _myLeftBitmap;
        private Bitmap _myRightBitmap;
        private MasterDataManagement _dtMgmt = null;
        private List<PropertiesValue> _propValue = null;
        private string _styleId = string.Empty;
        private string _shpId = string.Empty;
        private string _colorId = string.Empty;
        private string _erBackId = string.Empty;
        private bool _chkEmptyValue = false;
        private string _nextKeyId = string.Empty;
        private string _erLeftPostition = string.Empty;
        private string _erRightPostition = string.Empty;
        private Color _bgColor;
        private string _frontFile = string.Empty;
        private string _sideFile = string.Empty;
        private string _sizeFile = string.Empty;
        private string _sampleFile = string.Empty;
        private string _leftFile = string.Empty;
        private string _rightFile = string.Empty;
        private int _status;
        private string _folderEarrings = string.Empty;

        private string _erCodeForEdit = string.Empty;

        public frmEarringMaster()
        {
            InitializeComponent();
        }

        public frmEarringMaster(string erCode)
        {
            InitializeComponent();
            _erCodeForEdit = erCode;
        }

        private void frmEarringMaster_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_erCodeForEdit))
            {
                //Load Data to ComboBox
                //Style
                this.GetEarringsStyle();

                //Shape
                this.GetEarringsShape();

                //Color
                this.GetEarringsColor();

                //Earrings Back
                this.GetEarringsBack();
            }
            else
            {
                this.LoadDataEarringsForEdit();
            }
        }

        private void GetEarringsStyle()
        {
            _dtMgmt = MasterDataManagement.InstanceCreation();
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_ERSTY);

            PropertiesValue styVal = new PropertiesValue();
            styVal.KeyId = "0";
            styVal.Name = "--กรุณาเลือกรูปแบบต่างหู--";
            _propValue.Insert(0, styVal);

            cboStyle.DataSource = _propValue;
            cboStyle.ValueMember = "KeyId";
            cboStyle.DisplayMember = "Name";
            cboStyle.SelectedIndex = 0;
        }

        private void GetEarringsShape()
        {
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_ERSHP);

            PropertiesValue shpVal = new PropertiesValue();
            shpVal.KeyId = "0";
            shpVal.Name = "--กรุณาเลือกรูปทรงต่างหู--";
            _propValue.Insert(0, shpVal);

            cboShape.DataSource = _propValue;
            cboShape.ValueMember = "KeyId";
            cboShape.DisplayMember = "Name";
            cboShape.SelectedIndex = 0;
        }

        private void GetEarringsColor()
        {
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_JWCOR);

            PropertiesValue colVal = new PropertiesValue();
            colVal.KeyId = "0";
            colVal.Name = "--กรุณาเลือกสีต่างหู--";
            _propValue.Insert(0, colVal);

            cboColor.DataSource = _propValue;
            cboColor.ValueMember = "KeyId";
            cboColor.DisplayMember = "Name";
            cboColor.SelectedIndex = 0;
        }

        private void GetEarringsBack()
        {
            _propValue = new List<PropertiesValue>();
            _propValue = (List<PropertiesValue>)_dtMgmt.GetMasterEarringConfig<PropertiesValue>(GlobalValue.SHRTYP_ERBAC);

            PropertiesValue erbVal = new PropertiesValue();
            erbVal.KeyId = "0";
            erbVal.Name = "--กรุณาเลือกแป้นหลังต่างหู--";
            _propValue.Insert(0, erbVal);

            cboEarBack.DataSource = _propValue;
            cboEarBack.ValueMember = "KeyId";
            cboEarBack.DisplayMember = "Name";
            cboEarBack.SelectedIndex = 0;
        }

        private void CheckEmptyValue()
        {
            if (string.IsNullOrEmpty(txtearName.Text) || string.IsNullOrEmpty(_styleId)
                || string.IsNullOrEmpty(txtShortName.Text)
                || string.IsNullOrEmpty(_shpId) || string.IsNullOrEmpty(_colorId)
                || string.IsNullOrEmpty(_erBackId) || string.IsNullOrEmpty(txtMetal.Text)
                || string.IsNullOrEmpty(txtGemstone.Text) || string.IsNullOrEmpty(NUpDwnPrice.Text)
                || string.IsNullOrEmpty(lblLeftPoint.Text) || string.IsNullOrEmpty(lblRightPoint.Text))
            {
                _chkEmptyValue = true;
            }
            else
            {
                _chkEmptyValue = false;
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.ClearValue();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.ClearValue();
        }

        private void ClearValue()
        {
            foreach (Control ctl in tbllayoutData.Controls)
            {
                TextBox tb = ctl as TextBox;

                if (tb != null)
                {
                    tb.Clear();
                }

                TNumEditBox txtn = ctl as TNumEditBox;
                if (txtn != null)
                {
                    txtn.Clear();
                }
            }

            chkStatus.Checked = false;

            txtShortName.Clear();
            txtGemstone.Clear();
            txtMetal.Clear();

            txtearName.Clear();
            rtxtDetail.Clear();
            cboStyle.SelectedIndex = 0;
            cboShape.SelectedIndex = 0;
            cboColor.SelectedIndex = 0;
            cboEarBack.SelectedIndex = 0;

            picBxErFront.Image  = null;
            picBxErSide.Image = null;
            picBxErSize.Image = null;
            picBxErSample.Image = null;

            picBxLeft.Image = null;
            picBxLfPNG.Image = null;

            picBxRight.Image = null;
            picBxRgPNG.Image = null;
        }

        private void cboStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboStyle.SelectedIndex > 0)
            {
                PropertiesValue styVal = cboStyle.SelectedItem as PropertiesValue;
                _styleId = styVal.KeyId.ToString();                      
            }
        }

        private void cboShape_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboShape.SelectedIndex > 0)
            {
                PropertiesValue shpVal = cboShape.SelectedItem as PropertiesValue;
                _shpId = shpVal.KeyId.ToString();
            }
        }

        private void cboColor_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboColor.SelectedIndex > 0)
            {
                PropertiesValue colVal = cboColor.SelectedItem as PropertiesValue;
                _colorId = colVal.KeyId.ToString();
            }
        }

        private void cboEarBack_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboEarBack.SelectedIndex > 0)
            {
                PropertiesValue erBVal = cboEarBack.SelectedItem as PropertiesValue;
                _erBackId = erBVal.KeyId.ToString();
            }
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            this.CheckEmptyValue();

            if (_chkEmptyValue)
            {
                MessageBox.Show("กรุณากรอกหรือระบุข้อมูลให้ครบถ้วน");
            }
            else
            {
                string shortName = GetStlyeShortName();

                _nextKeyId = ValueUtil.GetNextKeyEarrings(_styleId, shortName);

                if (cboStyle.Text == "ต่างหูสตั๊ด")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Stud");
                }
                if (cboStyle.Text == "ต่างหูแบบครัสเตอร์")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Cluster");
                }
                if (cboStyle.Text == "ต่างหูแบบหยดน้ำ")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Drop");
                }
                if (cboStyle.Text == "ต่างหูแบบห้อยยาวกว้าง")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Wide Dangel");
                }
                if (cboStyle.Text == "ต่างหูแบบห้อยยาวแคบ")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Narrow Dangle");
                }
                if (cboStyle.Text == "ต่างหูแบบระย้า")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Chanderlier");
                }
                if (cboStyle.Text == "ต่างหูแบบห่วง")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Hoop");
                }
                if (cboColor.Text == "ต่างหูแบบห่วงเล็ก")
                {
                    _folderEarrings = Path.Combine(Resources.EarringsPath, "Huggies");
                }         

                this.SaveData();

                this.ClearValue();

                MessageBox.Show("บันทึกเรียบร้อย");
            }
        }
        private void SaveData()
        {
            //ชื่อไฟล์รูป
            //รูปด้านหน้า
            //Upload Earrings Image File to Server
            if (picBxErFront.Image != null)
            {
                _frontFile = Path.Combine(_folderEarrings, _nextKeyId + "-F.png");
                picBxErFront.Image.Save(_frontFile, ImageFormat.Png);
            }
            //รูปด้านข้าง
            if (picBxErSide.Image != null)
            {
                _sideFile = Path.Combine(_folderEarrings, _nextKeyId + "-S.png");
                picBxErSide.Image.Save(_sideFile, ImageFormat.Png);
            }
            //รูปวัดขนาด
            if (picBxErSize.Image != null)
            {
                _sizeFile = Path.Combine(_folderEarrings, _nextKeyId + "-Z.png");
                picBxErSize.Image.Save(_sizeFile, ImageFormat.Png);
            }
            //รูปใส่กับนางแบบ
            if (picBxErSample.Image != null)
            {
                _sampleFile = Path.Combine(_folderEarrings, _nextKeyId + "-M.png");
                picBxErSample.Image.Save(_sampleFile, ImageFormat.Png);
            }
            //รูปต่างหูข้างซ้าย
            if (picBxLfPNG.Image != null)
            {
                _leftFile = Path.Combine(_folderEarrings, _nextKeyId + "-L.png");
                picBxLfPNG.Image.Save(_leftFile);
            }
            //รูปต่างหูข้างขวา
            if (picBxRgPNG.Image != null)
            {
                _rightFile = Path.Combine(_folderEarrings, _nextKeyId + "-R.png");
                picBxRgPNG.Image.Save(_rightFile);
            }

            object nullValue = DBNull.Value;

            SqlParameter[] sqlParams = new SqlParameter[] 
                {
                    new SqlParameter("@KeyId", _nextKeyId) ,
                    new SqlParameter("@Name",txtearName.Text),
                    new SqlParameter("@StyId", _styleId),
                    new SqlParameter("@ShpId", _shpId),
                    new SqlParameter("@ColId", _colorId),
                    new SqlParameter("@ErBId", _erBackId),
                    new SqlParameter("@Width", txtNWidth.Text),
                    new SqlParameter("@Lenght", txtNLenght.Text),
                    new SqlParameter("@Price", NUpDwnPrice.Text),
                    new SqlParameter("@Quatity", txtNQuantity.Text),   
                    new SqlParameter("@ShortName",txtShortName.Text),
                    new SqlParameter("@Gemstone",txtGemstone.Text),
                    new SqlParameter("@Metal",txtMetal.Text),
                    new SqlParameter("@Detail", string.IsNullOrEmpty(rtxtDetail.Text)? nullValue : rtxtDetail.Text),
                    new SqlParameter ("@Status",_status),
                    new SqlParameter("@LeftPosition", _erLeftPostition),
                    new SqlParameter("@RightPosition", _erRightPostition),
                    new SqlParameter("@ImgFront",string.IsNullOrEmpty(Path.GetFileName(_frontFile)) ? nullValue: Path.GetFileName(_frontFile)),
                    new SqlParameter("@ImgSide",string.IsNullOrEmpty(Path.GetFileName(_sideFile)) ? nullValue : Path.GetFileName(_sideFile)),
                    new SqlParameter("@ImgSize",string.IsNullOrEmpty(Path.GetFileName(_sizeFile)) ? nullValue : Path.GetFileName(_sizeFile)),
                    new SqlParameter("@ImgSample",string.IsNullOrEmpty(Path.GetFileName(_sampleFile)) ? nullValue : Path.GetFileName(_sampleFile)),
                    new SqlParameter("@ImgLeft",string.IsNullOrEmpty(Path.GetFileName(_leftFile)) ? nullValue : Path.GetFileName(_leftFile)),
                    new SqlParameter("@ImgRight",string.IsNullOrEmpty(Path.GetFileName(_rightFile)) ? nullValue : Path.GetFileName(_rightFile)),
                };
            _dtMgmt = MasterDataManagement.InstanceCreation();
            _dtMgmt.SaveEarrings(sqlParams);
        }

        private string GetStlyeShortName()
        {
            SqlParameter[] sqlParams = new SqlParameter[] 
                {
                    new SqlParameter("@Id", _styleId)
                };
            _dtMgmt = MasterDataManagement.InstanceCreation();
            string shortName = _dtMgmt.GetShortName(sqlParams);
            return shortName;
        }

        private void btnUpFront_Click(object sender, EventArgs e)
        {

            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxErFront.Image = Image.FromFile(openFD.FileName);
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void btnUpLeft_Click(object sender, EventArgs e)
        {
            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxLeft.Image = Image.FromFile(openFD.FileName);

            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void btnDelLeftBg_Click(object sender, EventArgs e)
        {
            Bitmap myBitmap = new Bitmap(picBxLeft.Image);

            // Get the color of a background pixel.
            Color backColor = _bgColor; //myBitmap.GetPixel(1, 1);

            // Make backColor transparent for myBitmap.
            myBitmap.MakeTransparent(backColor);

            picBxLfPNG.Image = myBitmap;
            //string fileName = Path.Combine(Resources.EarringsPath, "Test.png");
            //picBxLfPNG.Image.Save(fileName);
        }

        private void btnDelRightBg_Click(object sender, EventArgs e)
        {
            Bitmap myBitmap = new Bitmap(picBxRight.Image);

            // Get the color of a background pixel.
            Color backColor = _bgColor; //myBitmap.GetPixel(1, 1);

            // Make backColor transparent for myBitmap.
            myBitmap.MakeTransparent(backColor);

            picBxRgPNG.Image = myBitmap;
        }

        private void btnUpRight_Click(object sender, EventArgs e)
        {
            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxRight.Image = Image.FromFile(openFD.FileName);
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void picBxLeft_MouseDown(object sender, MouseEventArgs e)
        {
            _myLeftBitmap = Win32APICall.GetDesktop();
        }

        private void picBxLeft_MouseUp(object sender, MouseEventArgs e)
        {
            _bgColor = _myLeftBitmap.GetPixel(MousePosition.X, MousePosition.Y);
            label17.ForeColor = _bgColor;
        }
        private void picBxRight_MouseDown(object sender, MouseEventArgs e)
        {
            _myRightBitmap = Win32APICall.GetDesktop();
        }

        private void picBxRight_MouseUp(object sender, MouseEventArgs e)
        {
            _bgColor = _myRightBitmap.GetPixel(MousePosition.X, MousePosition.Y);
            label4.ForeColor = _bgColor;
        }

        private void picBxLfPNG_Click(object sender, EventArgs e)
        {
            MouseEventArgs me = (MouseEventArgs)e;
            Point lfPoint = me.Location;
            _erLeftPostition = lfPoint.X.ToString() + ":" + lfPoint.Y.ToString();
            lblLeftPoint.Text = _erLeftPostition;
        }

        private void picBxRgPNG_Click(object sender, EventArgs e)
        {
            MouseEventArgs me = (MouseEventArgs)e;
            Point rgPoint = me.Location;
            _erRightPostition = rgPoint.X.ToString() + ":" + rgPoint.Y.ToString();
            lblRightPoint.Text = _erRightPostition;
        }

        private void chkStatus_CheckedChanged(object sender, EventArgs e)
        {
            if (chkStatus.Checked)
            {
                _status = 1;
            }
            else
            {
                _status = 0;
            }
        }

        private void btnSide_Click(object sender, EventArgs e)
        {
            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxErSide.Image = Image.FromFile(openFD.FileName);
                _sideFile = Path.GetFileName(openFD.FileName);
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void btnUpSize_Click(object sender, EventArgs e)
        {
            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxErSize.Image = Image.FromFile(openFD.FileName);
                _sizeFile = Path.GetFileName(openFD.FileName);
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void btnUpSample_Click(object sender, EventArgs e)
        {
            openFD.Filter = "JPEG Compressed Image (*.jpg|*.jpg" + "|GIF Image(*.gif|*.gif" + "|Bitmap Image(*.bmp|*.bmp" + "|Portable Network Graphics(*.png|*.png";
            openFD.Multiselect = true;
            openFD.FilterIndex = 1;
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                picBxErSample.Image = Image.FromFile(openFD.FileName);
                _sampleFile = Path.GetFileName(openFD.FileName);
            }
            else
            {
                MessageBox.Show("Operation Canceled");
            }
        }

        private void LoadDataEarringsForEdit()
        {
            //LoadData
        }

        private void button5_Click(object sender, EventArgs e)
        {
            MessageBox.Show(picBxLfPNG.Size.Width.ToString());
        }

        private void btnFrontZoom_Click(object sender, EventArgs e)
        {
            //frmZoomImage zoom = frmZoomImage.GetForm();
        }
    }

    

    public class Win32APICall
{
	[DllImport("gdi32.dll",EntryPoint="DeleteDC")]
	public static extern IntPtr DeleteDC(IntPtr hdc);

	[DllImport("gdi32.dll",EntryPoint="DeleteObject")]
	public static extern IntPtr DeleteObject(IntPtr hObject);

	[DllImport("gdi32.dll",EntryPoint="BitBlt")]
	public static extern bool BitBlt(IntPtr hdcDest,int nXDest,
		int nYDest,int nWidth,int nHeight,IntPtr hdcSrc,
		int nXSrc,int nYSrc,int dwRop);

	[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleBitmap")]
	public static extern IntPtr CreateCompatibleBitmap(IntPtr hdc, 
		int nWidth, int nHeight);

	[DllImport ("gdi32.dll",EntryPoint="CreateCompatibleDC")]
	public static extern IntPtr CreateCompatibleDC(IntPtr hdc);

	[DllImport ("gdi32.dll",EntryPoint="SelectObject")]
	public static extern IntPtr SelectObject(IntPtr hdc,IntPtr hgdiobjBmp);

	[DllImport("user32.dll", EntryPoint="GetDesktopWindow")]
	public static extern IntPtr GetDesktopWindow();

	[DllImport("user32.dll",EntryPoint="GetDC")]
	public static extern IntPtr GetDC(IntPtr hWnd);

	[DllImport("user32.dll",EntryPoint="GetSystemMetrics")]
	public static extern int GetSystemMetrics(int nIndex);

	[DllImport("user32.dll",EntryPoint="ReleaseDC")]
	public static extern IntPtr ReleaseDC(IntPtr hWnd,IntPtr hDC);

	public static Bitmap GetDesktop()
	{
		int screenX;
		int screenY;
		IntPtr hBmp;
		IntPtr  hdcScreen = GetDC(GetDesktopWindow());
		IntPtr hdcCompatible = CreateCompatibleDC(hdcScreen);

		screenX = GetSystemMetrics(0);
		screenY = GetSystemMetrics(1);
		hBmp = CreateCompatibleBitmap(hdcScreen, screenX, screenY);

		if (hBmp!=IntPtr.Zero)
		{
			IntPtr hOldBmp = (IntPtr) SelectObject(hdcCompatible, hBmp);
			BitBlt(hdcCompatible, 0, 0,screenX,screenY, hdcScreen, 0, 0,13369376);
			
			SelectObject(hdcCompatible, hOldBmp);
			DeleteDC(hdcCompatible);
			ReleaseDC(GetDesktopWindow(), hdcScreen);
			
			Bitmap bmp = System.Drawing.Image.FromHbitmap(hBmp); 
			
			DeleteObject(hBmp);
			GC.Collect();
			
			return bmp;
		}
		
		return null;
	}
}
}
